package com.fingard.dsp.bank.directbank.gdb01;


import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import com.fingard.FGBiz;
import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.DirectBase;
import com.fingard.net.ITcpClient;
import com.fingard.net.TcpPortClient;
import com.fingard.net.TcpReceiver;
import com.fingard.net.WebRequest;
import com.fingard.text.StringHelper;
import com.fingard.util.TransIDHelper;
import com.fingard.xml.XmlTextWriter;


public class GDB01Base extends DirectBase implements ITcpClient {

    private static TransIDHelper idHelper = new TransIDHelper(1, 999);

    protected String getQryTransID() {
        Date tmpDateNow = new Date();
        return Format.DateTime12Year2Format.format(tmpDateNow) + idHelper.getNextIDStr();
    }

    protected void writeCommonHeader(XmlTextWriter xmlWriter, GDB01Header p_bankHeader) throws Exception {
        if (StringHelper.isNullOrEmpty(p_bankHeader.entSeqNo)) {
            throw new Exception("未赋值entSeqNo");
        }
        if (StringHelper.isNullOrEmpty(p_bankHeader.tranCode)) {
            throw new Exception("未赋值tranCode");
        }
        Date tmpDateNow = new Date();
        xmlWriter.writeStartDocByDeclaration("<?xml version=\"1.0\" encoding=\"gbk\" ?>");
        xmlWriter.writeStartElement("BEDC");
        xmlWriter.writeStartElement("Message");
        xmlWriter.writeStartElement("commHead");
        xmlWriter.writeElementString("tranCode", p_bankHeader.tranCode);
        xmlWriter.writeElementString("cifMaster", bankFront.org);//客户号
        xmlWriter.writeElementString("entSeqNo", p_bankHeader.entSeqNo);
        xmlWriter.writeElementString("tranDate", Format.Date8Format.format(tmpDateNow));
        xmlWriter.writeElementString("tranTime", Format.Time6Format.format(tmpDateNow));
        xmlWriter.writeElementString("retCode", p_bankHeader.retCode);
        xmlWriter.writeElementString("entUserId", bankFront.operator);//操作员号
        xmlWriter.writeElementString("password", bankFront.loginPasswd);
        xmlWriter.writeEndElement();
    }

    protected String getCharset() {
        return getBankConfig().getCharset("GBK");
    }

    protected String[] sendToBank(String p_reqStr) throws Exception {

        String[] retStr = new String[]{"", ""};

        WriteBankLogLn("2.提交银行的地址：" + bankFront.serverIP + ":" + bankFront.serverPort);

        //发送银行前置
        TcpPortClient tmpClient = new TcpPortClient(bankFront.serverIP, Integer.parseInt(bankFront.serverPort), this);
        String tmpCharset = getCharset();
        byte[] tmpBytesBody = p_reqStr.getBytes(tmpCharset);

        WriteBankLogStep2(p_reqStr);
        TcpReceiver tmpReceiver = tmpClient.sendMessage(tmpBytesBody);
        retStr[0] = tmpReceiver.connState;
        if (tmpReceiver.recBytes != null) {
            retStr[1] = new String(tmpReceiver.recBytes, 0, tmpReceiver.readedLength, tmpCharset);
            WriteBankLogStep3(retStr[1]);
        } else {
            retStr[1] = tmpReceiver.getConnMsg();
        }
        if (!tmpReceiver.isCompleted) {
            WriteBankLogLn(tmpReceiver.getConnMsg());
        }
        return retStr;
    }

    public void getContentLength(TcpReceiver p_receiver) throws Exception {
        if (p_receiver.contentLength == -1) {
            String tmpCharset = getCharset();
            String tmpRecNow = new String(p_receiver.recBytes, 0, p_receiver.readedLength, tmpCharset);
            if (tmpRecNow.indexOf("</BEDC>") >= 0) {
                p_receiver.contentLength = p_receiver.readedLength;
                p_receiver.contentStartIndex = 0;
            }
        }
    }

    public String translateRetCode(String p_retCode) {
        try {
            return getBankConfig().getMapValueByKey("retCodeTranslate", p_retCode);
        } catch (Exception ex) {
            return "";
        }
    }

    //上送格式为json格式
    protected String[] sendToATS(String jsonData) throws Exception {
        String[] retStr = new String[]{"", ""};
        WriteBankLogLn("2.提交ATS的地址：" + FGBiz.dspCenter.dspSet.receiptPushServerUrl);


        //发送银行前置
        WebRequest tmpRequest = new WebRequest(FGBiz.dspCenter.dspSet.receiptPushServerUrl);
        tmpRequest.setConnectTimeout(60000);
        tmpRequest.setRequestProperty("connection", "Close");
        tmpRequest.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        String charsetName = getCharset();
        WriteBankLogLn("3.推送给ATS的json数据" + jsonData);
        byte[] tmpWriteBytes = jsonData.getBytes(charsetName);
        retStr = tmpRequest.upload(tmpWriteBytes, charsetName);
        WriteBankLogLn("4.返回的数据" + retStr[1]);

        return retStr;
    }

    public static String getLastDay(Date date) throws Exception{
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        int day = calendar.get(Calendar.DATE);
        //                      此处修改为+1则是获取后一天
        calendar.set(Calendar.DATE, day - 1);

        String lastDay = sdf.format(calendar.getTime());
        return lastDay;
    }
}
